﻿using Developer.Service;
using Super.Framework.Common;
using Super.Framework.Common.Web;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Developer.Web.Controllers
{
    public class BookController : BaseController
    {
        // GET: Book
        public ActionResult Detail(int bookId)
        {
            var book = BookService.GetAll().Find(bookId);
            return View(book);
        }

        public ActionResult InBorrow()
        {
            var id = Query.Value("uid").ToInt();
            var borrowBook = BorrowListService.GetAll().Where(a => a.UserId == id && a.ReturnTime == null);
            return View(borrowBook);
        }

        public ActionResult History()
        {
            var id = Query.Value("uid").ToInt();
            var borrowBook = BorrowListService.GetAll().Where(a => a.UserId == id);
            return View(borrowBook);
        }
        public ActionResult OrderOnline()
        {
            //var noneLeftBook = BookService.GetAll().Where(a => a.BookGits.FirstOrDefault().Remain == 0);
            var leftBooks = BaseService<Entity.BookGits>.GetAll().Where(a => a.Remain > 0).Select(a => a.Books);
            return View(leftBooks);
        }

        [HttpPost]
        public JsonResult AddOrder()
        {
            var bookId = Query.Value("bid").ToInt();
            var uid = Query.Value("uid").ToInt();
            if(!Request.IsAjaxRequest())
            {
                return Json("bad request", JsonRequestBehavior.AllowGet);
            }
            
            if (uid == 0)
            {
                return Json(new { error = "请先登录"}, JsonRequestBehavior.AllowGet);
            }
            
            var ordertemp = OrderTempService.GetAll().Where(a => a.UserId == uid && a.IsAbort == false);
            if(ordertemp != null)
            {
                foreach(var item in ordertemp)
                {
                    if(item.BookId == bookId)
                    {
                        return Json(new { error = "请勿重复添加" }, JsonRequestBehavior.AllowGet);
                    }
                }
            }
            OrderTempService.Add(new Entity.OrderTemps
            {
                UserId = uid,
                BookId = bookId,
                IsAbort = false
            });
            
            return Json(new { success = "已添加"},JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult AddFav()
        {
            var bid = Query.Value("bid").ToInt();
            var uid = Query.Value("uid").ToInt();
            var existFav = FavoriteService.GetAll().Where(a => a.UserId == uid);
            if (existFav != null)
            {
                foreach(var item in existFav)
                {
                    if (item.BookId == bid)
                    {
                        return Json(new { error = "请勿重复添加" }, JsonRequestBehavior.AllowGet);
                    }
                }
            }
            FavoriteService.Add(new Entity.Favorites
            {
                BookId = bid,
                UserId = uid,
                CreateTime = DateTime.Now
            });
            return Json(new { success = "添加成功" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 购物车
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderList(int uid)
        {
            var userId = Query.Value("uid").ToInt();
            if (userId == 0)
            {
                ShowMsg("请先登录", MessageItemType.Error);
                return Redirect("/index/login");
            }
            var orderlist = OrderTempService.GetAll().Where(a=>a.UserId == userId && a.IsAbort == false);
            return View(orderlist);
        }

        [HttpPost]
        public bool Order()
        {
            var userId = Query.Value("uid").ToInt();
            var books = Query.Value("bookIds[]").Split(',');
            var nowtime = DateTime.Now;
            var orderId = nowtime + "" + userId + new Random(10);
            if (books.Length < 1 ) return false;
            foreach ( var b in books)
            {
                BorrowListService.Add(new Entity.Borrowings {
                      BookId = int.Parse(b),
                      CreateTime = nowtime,
                      OrderId = orderId,
                      UserId = userId
                });
            }
            return true;
        }

        public ActionResult DeleteOrder()
        {
            var id = Query.Value("id").ToInt(0);
            var model = SysInfo.DB.OrderTemps.SingleOrDefault(a => a.Id == id);
            SysInfo.DB.OrderTemps.Remove(model);
            SysInfo.DB.SaveChanges();
            //ShowMsg("删除成功!", MessageItemType.Right);
            return RedirectToAction("Orderlist", "Book");
        }


        public ActionResult Navigation()
        {
            var alltypes = BookTypeService.GetAll().Where(a=>a.IsAbort == false);
            return View(alltypes);
        }

        public ActionResult NavigationBooks(int Id)
        {
            var nid = Query.Value("Id").ToInt();
            var books = BookTypeService.GetAll().Find(nid).Books.Where(a => a.IsAbort == false);
            return View(books);
        }
        [HttpPost]
        public JsonResult AddBorrowing()
        {
            var uid = Query.Value("uid").ToInt();
            var ordernum = GetOrderNum();
           
            //var orderid = OrderService.GetAll().FirstOrDefault(a => a.Num == ordernum).Id;
            var tempOrder = OrderTempService.GetAll().Where(b=>b.UserId == uid);
            //foreach(var t in tempOrder)
            //{
            //    var a = OrderTempService.GetAll
            //    OrderTempService.Change(t);
            //}
            foreach(var temp in tempOrder)
            {
                var t = OrderTempService.GetAll().Find(temp.Id);
                t.IsAbort = true;
                SysInfo.DB.Orders.Add(new Entity.Orders
                {
                    UserId = uid,
                    State = 0,
                    Num = ordernum,
                    CreateTIme = DateTime.Now,
                    BookiId = temp.BookId
                });
                SysInfo.DB.Borrowings.Add(new Entity.Borrowings
                {
                    BookId = temp.BookId,
                    UserId = uid,
                    CreateTime = DateTime.Now,
                    OrderId = ordernum,
                });
                var BGit = BaseService<Entity.BookGits>.GetAll().FirstOrDefault(c => c.BookId == temp.BookId);
                BGit.Remain -= 1;
            }
            SysInfo.DB.SaveChanges();
          
            return Json(new { success = "订购成功！" }, JsonRequestBehavior.AllowGet);

        }

        public ActionResult WhatNews()
        {
            var newbooks = BookService.GetAll().Where(a => a.IsAbort == false).OrderBy(a => a.CreateTime);
            return View(newbooks);
        }

        public ActionResult SearchResult()
        {
            var key = Query.Value("key");
            var result = BookService.GetAll().Where(a => a.Name == key && a.IsAbort == false).OrderBy(a => a.PY);
            return View(result);
        }

        public static object _lock = new object();
        public static int count = 1;
        public string GetOrderNum()
        {
            lock (_lock)
            {
                if(count >= 10000)
                {
                    count = 1;
                }
                var number = "P" + DateTime.Now.ToString("yyMMddHHmmss") + count.ToString("0000");
                count++;
                return number;
            }
        }
    }
}